package vashion.azeroth.back.controller.item;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import vashion.azeroth.activity.manager.GlobalActivityInfoManager;
import vashion.azeroth.back.controller.base.BaseController;
import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.core.activity.*;
import vashion.azeroth.core.activity.query.ActivityExtendQueryDO;
import vashion.azeroth.core.activity.query.ActivityInfoQueryDO;
import vashion.azeroth.core.pojo.AttributeUtils;
import vashion.azeroth.core.result.ApiResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动服务接口
 *
 * @param <T>
 */
@Controller
@RequestMapping("/back/activity")
public class BackActivityController<T> extends BaseController {

    private final static Logger log = LoggerFactory.getLogger(BackActivityController.class);

    @Autowired
    private GlobalActivityInfoManager globalActivityManager;


    @RequestMapping("getActivityList.htm")
    @ResponseBody
    public ApiResult<List<GlobalActivityInfoDO>> getActivityList(ModelMap modelMap,
                                                                 HttpServletResponse response,
                                                                 HttpServletRequest request,
                                                                 @ModelAttribute("activityInfoQueryDO")
                                                                 ActivityInfoQueryDO activityInfoQueryDO) {
        try {
            return globalActivityManager.queryAllActivityByType(activityInfoQueryDO);
        } catch (Exception e) {
            log.error("globalActivityManager.createGlobalActivity error", e);
            return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    @RequestMapping("queryExtendList.htm")
    @ResponseBody
    public ApiResult<List<GlobalActivityExtendInfoDO>> queryExtendList(ModelMap modelMap,
                                                                       HttpServletResponse response,
                                                                       HttpServletRequest request,
                                                                       @ModelAttribute("activityExtendQueryDO")
                                                                       ActivityExtendQueryDO activityExtendQueryDO) {
        try {
            return globalActivityManager.queryEffectExtendInfoList(activityExtendQueryDO);
        } catch (Exception e) {
            log.error("globalActivityManager.createGlobalActivity error", e);
            return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    @RequestMapping("insertActivity.htm")
    @ResponseBody
    public ApiResult<Long> insertActivity(ModelMap modelMap,
                                          HttpServletResponse response,
                                          HttpServletRequest request,
                                          @ModelAttribute("globalActivityInfoDO") GlobalActivityInfoDO globalActivityInfoDO) {
        try {

            globalActivityInfoDO.setAttributes("");
            globalActivityInfoDO.setSchemaInfo(ActiveSchemaEnum.valueOf(
                    globalActivityInfoDO.getActivityType()).getAttributes());
            globalActivityInfoDO.setStatus(1);
            globalActivityInfoDO.setUnitType(1);

            long id = globalActivityManager.createGlobalActivity(globalActivityInfoDO, getLoginUserId(request));
            return ApiResult.newSuccessResult(id);
        } catch (Exception e) {
            log.error("globalActivityManager.createGlobalActivity error", e);
            return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
        }
    }

    /**
     * 通过上传的excel填充数据详情
     *
     * @throws IOException
     */
    @RequestMapping("/insertExtend")
    @ResponseBody
    public ApiResult<Boolean> insertExtend(ModelMap modelMap,
                                           @RequestParam("activityId") Long activityId,
                                           HttpServletResponse response,
                                           HttpServletRequest request,
                                           @RequestParam(value = "file", required = true) MultipartFile file) throws Exception {

        try {
            List<LinkedHashMap<String, String>> excelData = this.getExcelData(file);
            log.error("excel 数据大小，excelData.size=" + excelData.size());
            if (CollectionUtils.isEmpty(excelData)) {
                return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(), CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
            }
            GlobalActivityInfoDO globalActivityInfoDO = globalActivityManager.queryActivityInfoById(activityId);
            List<GlobalActivityExtendInfoDO> activityExtendInfoDOList = buildExtendDOList(globalActivityInfoDO, excelData);
            return globalActivityManager.insertActivityExtendList(activityId, activityExtendInfoDOList, getLoginUserId(request));
        } catch (Exception e) {
            log.error("insertDataRowByExcel error ", e);
            return ApiResult.newSuccessResult(false);
        }

    }

    private List<GlobalActivityExtendInfoDO> buildExtendDOList(GlobalActivityInfoDO globalActivityInfoDO,
                                                               List<LinkedHashMap<String, String>> excelData) {

        List<GlobalActivityExtendInfoDO> resultList = Lists.newArrayList();
        Map<String, String> valueKeyMap = Maps.newHashMap();
        //导入活动详情
        // 查询投放定义
        ActiveSchemaEnum activeSchemaEnum = ActiveSchemaEnum.valueOf(globalActivityInfoDO.getActivityType());
        Map<String/**key*/, String/**value*/> attributeKeyToValueMap =
                AttributeUtils.getAttributeKeyToValueMap(activeSchemaEnum.getAttributes());

        for (Map.Entry<String, String> entry : attributeKeyToValueMap.entrySet()) {
            valueKeyMap.put(entry.getValue(), entry.getKey());
        }
        for (Map<String, String> map : excelData) {
            GlobalActivityExtendInfoDO activityExtendDO = new GlobalActivityExtendInfoDO();
            activityExtendDO.setActivityId(globalActivityInfoDO.getId());
            activityExtendDO.setActivityType(globalActivityInfoDO.getActivityType());
            activityExtendDO.setStartTime(globalActivityInfoDO.getStartTime());
            activityExtendDO.setEndTime(globalActivityInfoDO.getEndTime());
            Map<String, String> KeyValueMap = Maps.newHashMap();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (valueKeyMap.containsKey(entry.getKey())) {
                    KeyValueMap.put(valueKeyMap.get(entry.getKey()), entry.getValue());
                }
//                if (valueKeyMap.get(entry.getKey()).equals(ActiveConstant.SCHEMA_ITEM_ID) &&
//                        globalActivityInfoDO.getActivityType() == ActiveSchemaEnum.NEW_YANGTAO_INDEX_JINGXUAN.getActivityType()) {
//                    activityExtendDO.setUnitId(NumberUtils.toLong(entry.getValue()));
//                }
            }
            JSONObject json = new JSONObject();
            json.put(ActiveConstant.JSON_KEY, KeyValueMap);
            activityExtendDO.setContents(json.getJSONObject(ActiveConstant.JSON_KEY).toJSONString());
            resultList.add(activityExtendDO);
        }
        return resultList;
    }

    /**
     * 下载活动excel模板
     *
     * @throws IOException
     */
    @RequestMapping("/exportTemplateExcel")
    @ResponseBody
    public void exportTemplateExcel(ModelMap modelMap,
                                    @RequestParam("activityId") Long activityId,
                                    HttpServletResponse response) throws Exception {
        try {
            GlobalActivityInfoDO globalActivityInfoDO = globalActivityManager.queryActivityInfoById(activityId);
            // 查询投放定义
            ActiveSchemaEnum activeSchemaEnum = ActiveSchemaEnum.valueOf(globalActivityInfoDO.getActivityType());
            String schemaInfo = ActiveSchemaInfo.activityTypeToSchemaInfoMap.get(activeSchemaEnum.getActivityType());
            Map<String/**key*/, String/**value*/> attributeKeyToValueMap = AttributeUtils.getAttributeKeyToValueMap(schemaInfo);
            this.renderExcel(activeSchemaEnum.getDescName() + "-数据模板", Lists.newArrayList(attributeKeyToValueMap.values()), response);
        } catch (Exception e) {
            log.error("下载excel模板失败!", e);
        }
    }

    /**
     * 删除活动详情数据
     *
     * @throws IOException
     */
    @RequestMapping("/deleteExtend")
    @ResponseBody
    public ApiResult<Boolean> deleteExtend(ModelMap modelMap,
                                           @RequestParam("extendId") Long extendId,
                                           HttpServletResponse response,
                                           HttpServletRequest request) throws Exception {

        try {
            return globalActivityManager.deleteExtendInfo(extendId, getLoginUserId(request));
        } catch (Exception e) {
            log.error("insertDataRowByExcel error ", e);
            return ApiResult.newSuccessResult(false);
        }

    }

    /**
     * 删除活动详情数据
     *
     * @throws IOException
     */
    @RequestMapping("/deleteActivity")
    @ResponseBody
    public ApiResult<Boolean> deleteActivity(ModelMap modelMap,
                                             @RequestParam("id") Long id,
                                             HttpServletResponse response,
                                             HttpServletRequest request) throws Exception {

        try {
            return globalActivityManager.deleteGlobalActivity(id);
        } catch (Exception e) {
            log.error("deleteGlobalActivity error ", e);
            return ApiResult.newSuccessResult(false);
        }

    }
}
